package com.shop.mall.dao.impl;

import com.shop.mall.utils.MysqlDb;
import com.shop.mall.dao.GoodsDao;
import com.shop.mall.entity.Goods;
import com.shop.mall.utils.Pages;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyl
 * @version 1.0
 * @date 2019/4/23
 */
public class GoodsDaoImpl implements GoodsDao {

    @Override
    public List<Goods> getlist() {
        List<Goods> list = new ArrayList<Goods>();
        try {
            PreparedStatement ps = getConnection().prepareStatement("select * from goods");
            System.out.println("执行sql:" + ps);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Goods goods = new Goods();
                goods.setId(rs.getLong("id"));
                goods.setName(rs.getString("name"));
                goods.setInfo(rs.getString("info"));
                goods.setPrice(rs.getBigDecimal("price"));
                goods.setNum(rs.getInt("num"));
                goods.setCategory(rs.getString("category"));
                goods.setDescription(rs.getString("description"));
                goods.setCreator(rs.getString("creator"));
                goods.setCreate_time(rs.getString("create_time"));

                list.add(goods);
            }
            MysqlDb.closeAll(rs, ps, getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Pages getlist(int currentPage, int pageSize, String tableName, String orderBy) {
        List<Goods> list = new ArrayList<Goods>();
        Connection conn;
        try {
            conn = MysqlDb.getConnection();
            PreparedStatement ps = conn.prepareStatement("select * from goods");
            System.out.println("执行sql:" + ps);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Goods goods = new Goods();
                goods.setId(rs.getLong("id"));
                goods.setName(rs.getString("name"));
                goods.setInfo(rs.getString("info"));
                goods.setPrice(rs.getBigDecimal("price"));
                goods.setNum(rs.getInt("num"));
                goods.setCategory(rs.getString("category"));
                goods.setDescription(rs.getString("description"));
                goods.setCreator(rs.getString("creator"));
                goods.setCreate_time(rs.getString("create_time"));

                list.add(goods);
            }
            MysqlDb.closeAll(rs, ps, conn);
        } catch (Exception e) {
            System.out.println("异常：" + e.getMessage());
            throw new RuntimeException("异常:" + e.getMessage());
        }

        Pages page = new Pages();
        page.setList(list);
        return page;
    }

    private Connection getConnection() throws Exception {
        return MysqlDb.getConnection();
    }

}
